#include "custom_widget.h"
#include <QPainter>

CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent)
{

}

void CustomWidget::setData(const QVector<SqOutput> &data)
{
    inputData = data;
}

QSharedPointer<MTree> CustomWidget::getRoot(const QPoint &pos) const
{
    for (const auto &sqOutput : inputData)
    {
        if (sqOutput.rectangle.contains(pos))
        {
            return sqOutput.ptr;
        }
    }
    return QSharedPointer<MTree>();
}

void CustomWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    for (const auto &sqOutput : inputData)
    {
        painter.drawRect(sqOutput.rectangle);
        QString sizeInfo = showFollowedUnit(sqOutput.ptr->getFile().getSize());
        QString nameInfo = sqOutput.ptr->getFile().getName();
        QString text = nameInfo + "\n" + sizeInfo;
        QFont font = painter.font();
        QFontMetricsF metrics(font);
        QRectF textRect = metrics.boundingRect(text);
        qreal scaleFactor = qMin(sqOutput.rectangle.width() / textRect.width(), sqOutput.rectangle.height() / textRect.height());
        if (scaleFactor < 1.0)
        {
            font.setPointSizeF(font.pointSizeF() * scaleFactor);
            painter.setFont(font);
        }
        painter.drawText(sqOutput.rectangle, Qt::AlignCenter, text);
        if (scaleFactor < 1.0)
        {
            font.setPointSizeF(font.pointSizeF() / scaleFactor);
            painter.setFont(font);
        }
    }
}

void CustomWidget::mousePressEvent(QMouseEvent *event)
{
    QPoint pos = event->pos();
    QSharedPointer<MTree> userData = getRoot(pos);
    if (!userData.isNull())
    {
        emit ItemClicked(userData);
    }
}
